package com.kfh.ybracelet.location;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.SimpleAdapter;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.LocationList;
import com.kfh.ybracelet.bean.LocationsResBean;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.AbDateUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.DensityUtil;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.BatteryView;

import java.util.Date;
import java.util.List;


/**
 * 历史轨迹
 * Created by Aaron on 15/8/4.
 */
public class HistoryActivity extends BaseActivity implements AMap.InfoWindowAdapter {

    private long firstTimeOfDay = AbDateUtil.getFirstTimeOfDay();
    private TextView tv_right;
    private TextView tv_title;
    private String TAG = getClass().getSimpleName();
    private AMap aMap;
    private MapView mapView;
    private AMapLocationClient mLocationClient;
    private View windowView;
    private TextView tv_time_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_history);
//        mApplication.addActivity(this);
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);

        initWidget();
        //加载地图
        initMap(savedInstanceState);

        //默认获取0点到当前时间的历史轨迹
        getHistoryRecord(firstTimeOfDay, new Date().getTime());

    }

    private void initMap(Bundle savedInstanceState) {

        mapView = (MapView) findViewById(R.id.gdmap);
        mapView.onCreate(savedInstanceState);// 此方法必须重写if (aMap == null) {
        aMap = mapView.getMap();

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                Log.e(TAG, " +++ onMarkerClick +++ ");
                mLocMarker = marker;
                return false;
            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mLocMarker.isInfoWindowShown())
                    mLocMarker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
            }
        });

        aMap.setInfoWindowAdapter(this);

        //显示比例尺
        aMap.getUiSettings().setScaleControlsEnabled(true);
    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
//        iv_left.setImageResource(R.drawable.arrow_down);

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.today));
        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setText(getResources().getString(R.string.time_select));

        tv_time_info = (TextView) findViewById(R.id.tv_time_info);

        iv_left.setOnClickListener(this);
        tv_title.setOnClickListener(this);
        tv_right.setOnClickListener(this);

    }

    private TextView tv_barry;
    private TextView tv_time;
    private BatteryView iv_barry;
    private TextView adrress;

    /**
     * 获取历史轨迹信息
     */
    private void getHistoryRecord(long starTime, long endTime) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("startTime", starTime);
        j.put("endTime", endTime);

        LogUtil.e("tag", "startTime:" + new Date(starTime) + ",endTime:" + new Date(endTime));

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.GETCHILDLOCLIST,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            LocationsResBean locationsResBean = JSONObject.parseObject(str, LocationsResBean.class);

                            List<LocationList> locationList = locationsResBean.locationList;

                            if (locationList == null || locationList.size() == 0) {
                                showToast("未查询到该时间段的定位信息");

                                if (aMap != null)
                                    aMap.clear();

                                return;
                            }

                            //创建历史定位图标
                            createLocationMarks(locationList);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    /**
     * 创建历史定位图标
     *
     * @param locationList
     */
    private void createLocationMarks(List<LocationList> locationList) {
        if (aMap != null)
            aMap.clear();

//        //高德地图,画线的option
//        PolylineOptions options = new PolylineOptions();
//        options.width(20);//设置宽度

        LogUtil.e(TAG, "有" + locationList.size() + "条轨迹记录");

        //根据服务器返回的点的集合个数,创建多少个点
        for (int i = 0; i < locationList.size(); i++) {

            //创建点
            LatLng location = new LatLng(locationList.get(i).latitude, locationList.get(i).longitude);
            addMarker(location, locationList.get(i));
//            options.add(location);//添加画线的点
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));//移动到location位置,并设置缩放比例

        }

//        //用一个数组来存放颜色，渐变色，四个点需要设置四个颜色
//        List<Integer> colorList = new ArrayList<Integer>();
//        colorList.add(Color.GREEN);
//        options.color(getResources().getColor(R.color.color_5d));
//        aMap.addPolyline(options);//画线

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.tv_right:

                selectTimeQuantum(v);

                break;

            case R.id.tv_title:

                Intent intent = new Intent(this, ChooseDateActivity.class);
                startActivityForResult(intent, 24);

                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 24:

                if (data == null)
                    return;

                //选择的日期
                firstTimeOfDay = data.getLongExtra("date", 0);
                tv_title.setText(AbDateUtil.getStringByFormat(firstTimeOfDay, AbDateUtil.DATEFORMATYMD));
                selectTimeQuantum(tv_right);

                break;

        }

    }

    /**
     * 选择时间段
     */
    @Deprecated
    private void selectTimeQuantum(View v) {

        View popuView = View.inflate(this, R.layout.popup_choose_time_quantum, null);

        final PopupWindow areaPup = new PopupWindow(popuView,
                DensityUtil.dip2px(this, 120), DensityUtil.dip2px(this, 300));
//        areaPup.setContentView(popuView);
        areaPup.setOutsideTouchable(true);

        areaPup.setFocusable(true);
        areaPup.setBackgroundDrawable(new BitmapDrawable());
        //x y
        areaPup.showAsDropDown(v, 0, 0);

        ListView lv_time = (ListView) popuView.findViewById(R.id.lv_time);

        SimpleAdapter adapter = new SimpleAdapter(this, getResources().getStringArray(R.array.tims_quantum));

        lv_time.setAdapter(adapter);

        lv_time.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (areaPup != null && areaPup.isShowing())
                    areaPup.dismiss();

                //获取到选择的开始时间和结束时间
                long firstTime = firstTimeOfDay + (2 * 60 * 60 * 1000) * i;

                long lastTime = firstTime + (2 * 60 * 60 * 1000);

//                String s = tv_title.getText().toString();

                tv_time_info.setText(tv_title.getText().toString() + "的部分活动轨迹");

                getHistoryRecord(firstTime, lastTime);

            }
        });

    }

    private Marker mLocMarker;
    private BitmapDescriptor des = null;

    private void addMarker(LatLng latlng, LocationList locationList) {

        if (des == null) {
            Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                    R.mipmap.thumb);
            des = BitmapDescriptorFactory.fromBitmap(bMap);
        }

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setObject(locationList);
        mLocMarker.setTitle("title");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null)
            mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mapView != null)
            mapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mapView != null) {
            mapView.onPause();
            deactivate();
        }

    }

    @Override
    public void finish() {
        super.finish();

        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
    }

    public void deactivate() {
//        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }


    @Override
    public View getInfoWindow(Marker marker) {
        LayoutInflater inflater = getLayoutInflater();

        windowView = inflater.inflate(R.layout.alog_showbaby_location, null);
        windowView.setPadding(5, 5, 5, 5);
//        view.setBackgroundResource(R.drawable.ic_mylocation_bg);

        tv_barry = (TextView) windowView.findViewById(R.id.tv_barry);
        tv_time = (TextView) windowView.findViewById(R.id.tv_time);
        iv_barry = (BatteryView) windowView.findViewById(R.id.iv_barry);
        adrress = (TextView) windowView.findViewById(R.id.adrress);
        LocationList info = (LocationList) marker.getObject();

        if (info == null)
            return null;

        Log.d(TAG, "getInfoWindow markInfo :" + info.updateTime
                + "," + info._id
                + "," + info.battery
                + "," + info.sn
                + "," + info.latitude);

        tv_time.setText(AbDateUtil.getStringByFormat(info.updateTime, "yyyy-MM-dd HH:mm:ss"));
        adrress.setText(info.addressDescription);
        tv_barry.setText(info.battery + "%");

        if (!CommonUtils.isNull(info.battery)) {

            tv_barry.setText(info.battery + "%");
            int currentBattery = Integer.parseInt(info.battery);

            if (currentBattery <= 20) {//电量小于20变红

                iv_barry.setLength(35, 15, 5, 10, 1);
                iv_barry.setColor(Color.BLACK, Color.RED);

            } else { //大于20是绿的

                iv_barry.setLength(35, 15, 5, 10, 1);
                iv_barry.setColor(Color.BLACK, Color.GREEN);
            }

            if (currentBattery <= 5) {
                iv_barry.setPower(5);
            } else {
                iv_barry.setPower(currentBattery);
            }

        }

        return windowView;
    }

    @Override
    public View getInfoContents(Marker marker) {
//        if (infoView == null) {
//            infoView = new TextView(this);
//            infoView.setGravity(Gravity.CENTER);
//            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//        }
//        infoView.setText(babyName);
        Log.d(TAG, "getInfoContents markInfo :" + marker.toString());
        return null;
    }
}
